<template>
  <div class="map-wrap">
    <!-- <Map mapInstance="$map1" :mapConfig="mapConfig"></Map> -->
    <Map v-if="showMap" mapInstance="$map" :mapConfig="mapConfig"></Map>
    <div class="map-tool">
      <span v-for="(item, index) in mapTools" @click="mapToolAction(item.type)" :key="index">{{item.label}}</span>
      <select @change="changeCameraView">
        <option value="resetView">视角模式：无</option>
        <option value="setFixedView">固定视角</option>
        <option value="setFrontView">第一视角</option>
        <option value="setTrackView">第三视角</option>
      </select>
    </div>
    <Swipe ref="Swipe"></Swipe>
    <div v-show="false">
      <WebrtcVideo ref="webrtcVideo"></WebrtcVideo>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import mapConfig from "../cesium/mapConfig.js";
import { XYZtoLonlat } from "../utils/common.js";
import Map from "../cesium/Map.vue";
import Swipe from "./components/Swipe.vue";
import WebrtcVideo from "./components/WebrtcVideo.vue";
import { Zoom } from 'ol/control.js';
export default {
  components: {
    Map, Swipe, WebrtcVideo
  },
  data () {
    return {
      mapConfig,
      showMap: true,
      mapTools: [
        { type: "destroy", label: "销毁地图" },
        { type: "createTerrain", label: "添加地形" },
        { type: "MVTImageryProvider", label: "添加矢量切片" },
        { type: "click", label: "点击事件" },
        { type: "multiClick", label: "点击事件（获取多个）" },
        { type: "drawPoint", label: "绘制点" },
        { type: "drawPolyline", label: "绘制线" },
        { type: "drawPolygon", label: "绘制面" },
        { type: "measureLength", label: "测量长度" },
        { type: "measureArea", label: "测量面积" },
        { type: "measureHeight", label: "测量高度" },
        { type: "viewShed", label: "可视域分析" },
        { type: "VideoShed3D", label: "视频投影" },
        { type: "addTileset", label: "添加3dtiles模型" },
        { type: "addSpreadCircle", label: "添加扩散圆" },
        { type: "addScanCircle", label: "添加扫描圆" },
        { type: "startSwipe", label: "开启卷帘" },
        { type: "closeSwipe", label: "关闭卷帘" },
        { type: "createEntity", label: "创建Entity" },
        { type: "resetEntity", label: "重置Entity" },
        { type: "geojsonToEntities", label: "geojson转Entities" },
        { type: "getEntityByProperty", label: "根据属性获取entity" },
        { type: "lookAt", label: "视角追踪" },
        { type: "addParticleWindy", label: "添加风场" },
        { type: "removeParticleWindy", label: "移除风场" },
        { type: "addDroneModel", label: "添加动态模型" },
      ],
    }
  },
  mounted () {
    this.initMap();
    console.log('log--- this.$refs.webrtcVideo', this.$refs.webrtcVideo);
    this.$refs.webrtcVideo.playVideo("http://117.159.13.209:1880/index/api/webrtc?app=live&stream=1581F5FJD228K00A0486&type=play");
  },
  methods: {
    async initMap() {
      console.log('log--- this.$map', this.$map);

      this.showLayer = this.$map.createDataSource();
      this.testLayer = this.$map.createDataSource();
      this.modelLayer = this.$map.createDataSource();

      this.$map.flyToHome({duration: 0}).then(() => {
        console.log('log--- 定位到初始位置');
      });

      // this.$map.flyTo({
      //   lng: 114,
      //   lat: 34
      // }).then(() => {
      //   console.log('log--- 定位指定经纬度');
      // });

      // this.mapToolAction("addTileset");

      let lonlat = XYZtoLonlat(12, 3420, 1684);
      console.log('log--- lonlat', lonlat);
    },
    async mapToolAction(type) {
      if(type === "destroy") {
        this.showMap = false;
        // this.$map.destroy();
      }
      if(type === "createTerrain") {
        this.$map.viewer.terrainProvider = this.$map.createTerrain("http://data.marsgis.cn/terrain", {
          requestWaterMask: true
        });
      }
      if(type === "MVTImageryProvider") {
        this.MVTlayer = this.$map.addImageryLayer({
          type: "MVT",
          mapboxAccessToken: "pk.eyJ1Ijoic2hpd2IiLCJhIjoiY2t4NHEycHM3MmF3ZzJxcXJyNW1mdXh2cCJ9.Sf64I3o1xiJqqZCR9h229w",
          style: {
            "version": 8, //版本号（必填，且值必须为 8）
            "name": "blank", // 地图名称（可选，用于给 style 取名，方便阅读
            "sources": {
              "vector-source": {
                "type": "vector", // 类型（必填）
                "tiles": [ // 用于指定一个或多个切片数据源的请求地址（可选，和 TileJSON 中的 tiles 属性一致）
                  "http://localhost:8087/geoserver/gwc/service/tms/1.0.0/beijing%3Acoalpower_section_bak20230706@EPSG%3A900913@pbf/{z}/{x}/{y}.pbf"
                ],
                // "bounds": [-180, -85.051129, 180, 85.051129], // 边界坐标点（可选，用于限定切片的显示范围，默认值为 [-180,-85.051129,180,85.051129]）
                "scheme": "tms", // 切片坐标系方案（可选，可选值为 xyz、tms，默认值为 xyz）
                "minzoom": 0, // 最小层级（可选，默认值为 0）
                "maxzoom": 23, // 最大层级（可选，默认值为 22）
              }
            },
            "glyphs": "mapbox://fonts/mapbox/{fontstack}/{range}.pbf",
            "layers": [
              {
                "id": "coalpower_section_bak20230706", // 唯一 id （必填）
                "type": "line", // 类型（必填）
                "source": "vector-source", // 数据源的名称（除了 layer 的 type 为 background 外，source 必填） 
                "source-layer": "coalpower_section_bak20230706", // 数据源的图层（只有数据源 source 的 type 为 vector 时，才能设置 source-layer，其他类型的不可以设置）
                // "filter": ["==", "name", "10kV高庙路改造"], // 过滤（可选，用特定的表达式过滤指定的数据源的要素。具体的表达式详见 expression）
                "paint": { // 绘制类属性
                  "line-color": "#00ff00", // 线的颜色（可选，默认值为 #000000。如果设置了 line-pattern，则 line-color 将无效）
                  "line-width": 2, // 线的宽度（可选，值 >= 0，默认值为 1，单位：像素）
                }
              },
              {
                "id": "coalpower_section_bak20230706_label",
                "type": "symbol",
                "source": "vector-source",
                "source-layer": "coalpower_section_bak20230706",
                "paint": {
                  "text-color": "#ffffff"
                },
                "layout": {
                  "symbol-placement": "line",
                  "text-field": "{name}",
                  "text-size": 14,
                }
              }
            ]
          },
        });
        console.log('log--- this.MVTlayer', this.MVTlayer);
        setTimeout(() => {
          this.MVTlayer.imageryProvider.mapboxRenderer.setFilter('coalpower_section_bak20230706', ["in", "name", "MTBrVumrmOW6mei3r+aUuemAoA==", "MTBrVuWkp+eqnemTuui3r+aUuemAoA=="]);
          this.MVTlayer.imageryProvider.mapboxRenderer.setFilter('coalpower_section_bak20230706' + '_label', ["in", "name", "MTBrVumrmOW6mei3r+aUuemAoA==", "MTBrVuWkp+eqnemTuui3r+aUuemAoA=="]);
          this.MVTlayer.imageryProvider.mapboxRenderer.setPaintProperty('coalpower_section_bak20230706', "line-color", "#ffff00");
          this.MVTlayer.imageryProvider.mapboxRenderer.setPaintProperty('coalpower_section_bak20230706', "line-width", 2);
          this.MVTlayer.imageryProvider._reload();
        }, 1000)
      }
      if(type === "click") {
        this.$map.mapOnClick(async evt => {
          console.log('log--- evt', evt);
          let { entity, cartesian, center } = evt;
          
          this.$map.popup.open({
            content: "测试点击事件",
            position: center,
            offset: [0, 30],
          });

          // 获取矢量切片信息
          if(this.MVTlayer) {
            let zoom = this.$map.getZoom();
            let tileXY = this.MVTlayer.imageryProvider.tilingScheme.positionToTileXY(Cesium.Cartographic.fromCartesian(cartesian), zoom);
            let pickFeatures = await this.MVTlayer.imageryProvider.pickFeatures(tileXY.x, tileXY.y, zoom, cartographic.longitude, cartographic.latitude);
            console.log('log--- pickFeatures', pickFeatures);
          }
        });
      }
      if(type === "multiClick") {
        this.$map.mapOnMultiClick(evt => {
          console.log('log--- evt', evt);
          let { entities } = evt;
          let entity = entities.find(item => item.name == "测试区域");
          if(entity) {
            let center = this.$map.getEntityCenter(entity);
            let properties = this.$map.resetCesiumProperty(entity.properties);
            this.$map.popup.open({
              content: "测试点击事件",
              position: center,
              offset: [0, 30],
            });
          }
        });
      }
      if(type === "drawPoint") {
        this.$map.drawer.drawPoint({
          image: "https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
          // isAgain: true,
          // width: 30,
          // height: 50,
          // verticalOrigin: "TOP",
          // horizontalOrigin: "LEFT",
          // offset: [100, 100],
          clampToGround: true,
          callback: evt => {
            console.log('log--- evt', evt);
            let geojson = this.$map.drawer.positionToGeojson('Point', evt.position);
            console.log('log--- geojson', geojson);
          }
        });
      }
      if(type === "drawPolyline") {
        this.$map.drawer.drawPolyline({
          color: "#00ff00", 
          width: 3,
          // isAgain: true,
          callback: (evt) => {
            console.log('log--- evt', evt);
            let geojson = this.$map.drawer.positionToGeojson('LineString', evt.position);
            console.log('log--- geojson', geojson);
            let wkt = this.$map.geojsonToWkt(geojson);
            console.log('log--- wkt', wkt);
            // setTimeout(() => {
            //   this.$map.drawer.remove(evt.entity);
            // }, 2000);
            let center = this.$map.getEntityCenter(evt.entity);
            let point = this.$map.createEntity({
              position: center,
              billboard: {
                image: "https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
                // clampToGround: true,
              },
            });
            // this.testLayer.entities.add(point);
          }
        });
      }
      if(type === "drawPolygon") {
        this.$map.drawer.drawPolygon({
          color: "rgba(255,0,0,0.5)", 
          outlineColor: "#00ff00", 
          outlineWidth: 3,
          // isAgain: true,
          callback: (evt) => {
            console.log('log--- evt', evt);
            let cartesian = evt.cartesian.map(item => this.$map.cartesianToLnglat(item));
            console.log('log--- cartesian', cartesian);
            let geojson = this.$map.drawer.positionToGeojson('Polygon', evt.position);
            console.log('log--- geojson', geojson);
            let wkt = this.$map.geojsonToWkt(geojson);
            console.log('log--- wkt', wkt);
            let center = this.$map.getEntityCenter(evt.entity);
            let point = this.$map.createEntity({
              position: center,
              billboard: {
                image: "https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
                // clampToGround: true,
              },
            });
            // this.testLayer.entities.add(point);
          }
        });
      }
      if(type === "measureLength") {
        this.$map.measure.clear();
        this.$map.measure.drawLineMeasureGraphics({
          clampToGround: true,
          callback: (position, entity) => {
            console.log('log--- position', position);
            console.log('log--- entity', entity);
          }
        });
      }
      if(type === "measureArea") {
        this.$map.measure.clear();
        this.$map.measure.drawAreaMeasureGraphics({
          callback: (position, entity) => {
            console.log('log--- position', position);
            console.log('log--- entity', entity);
          }
        });
      }
      if(type === "measureHeight") {
        this.$map.measure.clear();
        this.$map.measure.drawTrianglesMeasureGraphics({
          callback: (position, entity) => {
            console.log('log--- position', position);
            console.log('log--- entity', entity);
          }
        });
      }
      if(type === "viewShed") {
        // 开启深度检测, 否则地形无效果
        this.$map.openTerrainDeepTest(true);
        
        this.viewShed = new Cesium.ViewShed(this.$map.viewer, {
          viewPosition: this.$map.lnglatToCartesian(113.30865847461958, 33.71617392431995, 220.45665203892226),
          viewDistance: 3000
        });
        console.log('log--- this.viewShed', this.viewShed);
      }
      if(type === "VideoShed3D") {
        // 开启深度检测, 否则地形无效果
        this.$map.openTerrainDeepTest(true);

        // let position = {x: 113.55661, y: 34.819168, z: 20};
        // this.cesiumVideo3d = new Cesium.VideoShed3D(this.$map.viewer, {
        //   url: "http://117.159.13.207:9666/webresource/video/fly_demo.mp4",
        //   position: position,
        //   rotation: { x: 1, y: 1 },
        //   alpha: 1,
        //   far: 200,
        //   debugFrustum: true
        // });
        // console.log('log--- this.cesiumVideo3d', this.cesiumVideo3d);
        
        this.VideoShed = new Cesium.VideoShed(this.$map.viewer, {
          // playUrl: "http://117.159.13.207:9666/webresource/video/fly_demo.mp4",
          videoElement: this.$refs.webrtcVideo.$el,
          viewPosition: this.$map.lnglatToCartesian(113.55661, 34.819168, 200),
          viewDistance: 10000,
          viewPitch: -45,
          horizontalViewAngle: 85,
          verticalViewAngle: 48
        });
        console.log('log--- this.VideoShed', this.VideoShed);
      }
      if(type === "addTileset") {
        if(this.tiles3d && this.tiles3d.ready) {
          this.$map.removePrimitive(this.tiles3d);
        }
        this.tiles3d = this.$map.add3DTileset({
          // url: "http://117.159.13.207:8203/models/hunanys/tileset.json",
          url: "http://117.159.13.207:8203/models/pingdingshan/tileset.json",
          // url: "http://117.159.13.207:8203/models/yaoshigou/tileset.json",
          // url: "http://117.159.13.207:8203/models/863/tileset.json",
          splitDirection: "RIGHT",
          height: 0,
          // lng: 111,
          // lat: 23,
          // debugShowBoundingVolume: true
        });
        console.log('log--- this.tiles3d',this.tiles3d );
        this.$map.flyToEntity(this.tiles3d, {
          duration: 2,
          pitch: -90,
          distance: 2000
        }).then(() => {
          let tileset = this.tiles3d;
          // 获取包围盒矩阵
          let halfAxes = tileset._root._boundingVolume._orientedBoundingBox.halfAxes;
          // 获取包围盒中心点
          let boxCenter = tileset._root._boundingVolume._orientedBoundingBox.center;
          
          // 计算x，y，z坐标
          let xaxis = Cesium.Matrix3.getColumn(halfAxes, 0, new Cesium.Cartesian3());
          let yaxis = Cesium.Matrix3.getColumn(halfAxes, 1, new Cesium.Cartesian3());
          let zaxis = Cesium.Matrix3.getColumn(halfAxes, 2, new Cesium.Cartesian3());

          let calcXaxis = new Cesium.Cartesian3();
          let calcYaxis = new Cesium.Cartesian3();
          let calcZaxis = new Cesium.Cartesian3(); // 左下角坐标
          // 计算包围盒左下角坐标
          Cesium.Cartesian3.subtract(boxCenter, xaxis, calcXaxis);
          Cesium.Cartesian3.subtract(calcXaxis, yaxis, calcYaxis);
          Cesium.Cartesian3.subtract(calcYaxis, zaxis, calcZaxis);
          
          // this.$map.viewer.entities.add({
          //   position: boxCenter,
          //   plane: {
          //     plane: new Cesium.Plane(Cesium.Cartesian3.UNIT_Z, 0.0),
          //     dimensions: new Cesium.Cartesian2(2000.0, 2000.0),
          //     material: Cesium.Color.RED.withAlpha(0.5),
          //     outline: true,
          //     outlineColor: Cesium.Color.YELLOW,
          //   },
          // });
          // this.$map.viewer.entities.add({
          //   position: calcZaxis,
          //   plane: {
          //     plane: new Cesium.Plane(Cesium.Cartesian3.UNIT_Z, 0.0),
          //     dimensions: new Cesium.Cartesian2(2000.0, 2000.0),
          //     material: Cesium.Color.RED.withAlpha(0.5),
          //     outline: true,
          //     outlineColor: Cesium.Color.YELLOW,
          //   },
          // });
        });
      }
      if(type === "addSpreadCircle") {
        let spreadEntity = this.$map.addSpreadCircle({
          layer: this.showLayer,
          minRange: 0,
          maxRange: 3000,
          interval: 20,
          image: require("../cesium/imgs/circle.png"),
          position: [113.55661, 34.819168]
        });
        console.log('log--- spreadEntity', spreadEntity);
        this.$map.flyToEntity(spreadEntity);

        // 纯颜色扩散效果
        this.showLayer.entities.add(this.$map.createEntity({
          position: [113.55661, 34.819168],
          circle: {
            radius: 3000,
            height: 0, //使用动态效果必须指定height，否则displayDistance无效
            // color: new Cesium.EllipsoidFadeMaterial(Cesium.Color.GREEN, 2000),
            color: new Cesium.CircleWaveMaterialProperty({
              // color: 'rgba(1, 213, 222, 0.6)', 
              color: 'rgba(0, 255, 0, 0.6)', 
              duration: 5000, 
              count: 1,
              // gradient: 0.1
            }),
            outlineColor: "#00ff00",
            outlineWidth: 2,
            displayDistance: [5000, Number.MAX_VALUE],
          }
        }));
      }
      if(type === "addScanCircle") {
        let scanEntity = this.$map.addScanCircle({
          layer: this.showLayer,
          radius: 3000,
          interval: 0.05,
          image: require("../cesium/imgs/scan.png"),
          position: [113.55661, 34.819168]
        });
        console.log('log--- scanEntity', scanEntity);
        this.$map.flyToEntity(scanEntity);
      }
      if(type === "startSwipe") {
        this.$map.startSwipe(); //使用默认的dom
        // this.$map.startSwipe(this.$refs.Swipe.$el); //使用传入的dom
      }
      if(type === "closeSwipe") {
        this.$map.closeSwipe();
      }
      if(type === "createEntity") {
        let entity = this.$map.createEntity({
          id: "createEntity",
          position: [113.55661, 34.819168],
          /**
           * 添加模型
           */
          // model: {
          //   url: "./model/fj.gltf",
          //   scale: 1,
          //   clampToGround: true
          // },
          // createModelEntity: () => {
          //   return this.$map.createModelEntity({
          //     url: "./model/fj.gltf",
          //     scale: 0.1
          //   });
          //   return new Cesium.Entity({
          //     model: {
          //       uri: "./model/fj.gltf",
          //       scale: 0.1
          //     }
          //   });
          // },
          /**
           * 添加圆
           */
          // circle: {
          //   radius: 100,
          //   // height: 100,
          //   color: "#ff0000",
          //   outlineWidth: 3,
          //   outlineColor: "#ffff00",
          //   displayDistance: [0, 2000]
          // },
          // createCircleEntity() {
          //   return new Cesium.Entity({
          //     ellipse: {
          //       semiMinorAxis: 100,
          //       semiMajorAxis: 100,
          //       height: 100,
          //       material: Cesium.Color.fromCssColorString("#ff0000"),
          //       outline: false
          //     }
          //   });
          // },
          /**
           * 图片
           */
          billboard: {
            image: "https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
            clampToGround: true,
            // width: 30,
            // height: 50,
            // verticalOrigin: "TOP",
            // horizontalOrigin: "LEFT",
            // offset: [-100, -100],
            // displayDistance: [0, 5000],
            // scaleDistance: [1500, 1.0, 150000, 0.25],
          },
          // 添加文字
          label: {
            text: "测试文字显示",
            size: 20,
            color: '#ffff00',
            backgroundColor: "rgba(0, 0, 0, 0.8)",
            offset: [0, -50],
            clampToGround: true,
            // scaleDistance: [1500, 1.0, 150000, 0.25],
          },
          // 添加线
          // polyline: {
          //   coordinates: [
          //     [ 111.69962882995605, 29.12888405176038, 100 ],
          //     [ 111.69842720031738, 29.1246103640853, 200 ],
          //     [ 111.70250415802002, 29.12191110140796, 300 ],
          //     [ 111.70456409454346, 29.123973044564462, 400 ]
          //   ],
          //   // coordinates: new Cesium.CallbackProperty((result) => {
          //   //   let coordinates = [
          //   //     [ 111.69962882995605, 29.12888405176038, 100 ],
          //   //     [ 111.69842720031738, 29.1246103640853, 200 ],
          //   //     [ 111.70250415802002, 29.12191110140796, 300 ],
          //   //     [ 111.70456409454346, 29.123973044564462, 400 ]
          //   //   ].map(item => {
          //   //     return this.$map.lnglatToCartesian(...item);
          //   //   });
          //   //   console.log('log--- coordinates', coordinates);
          //   //   return coordinates;
          //   // }, false),
          //   width: 5,
          //   // color: "#ffff00",
          //   color: new Cesium.PolylineGlowMaterialProperty({
          //     glowPower: 0.25,
          //     taperPower: 1,
          //     color: Cesium.Color.YELLOW,
          //   }),
          //   clampToGround: true, //设置贴地后，每个点的高度不生效
          // },
          // 添加面
          // polygon: {
          //   // coordinates: [[ 
          //   //   // [ 111.69962882995605, 29.12888405176038, 500 ],
          //   //   // [ 111.69842720031738, 29.1246103640853, 400 ],
          //   //   // [ 111.70250415802002, 29.12191110140796, 300 ],
          //   //   // [ 111.70456409454346, 29.123973044564462, 200 ],
          //   //   // [ 111.69962882995605, 29.12888405176038, 500 ],
          //   //   [ 111.69962882995605, 29.12888405176038 ],
          //   //   [ 111.69842720031738, 29.1246103640853 ],
          //   //   [ 111.70250415802002, 29.12191110140796 ],
          //   //   [ 111.70456409454346, 29.123973044564462 ],
          //   //   [ 111.69962882995605, 29.12888405176038 ],
          //   // ]],
          //   coordinates: new Cesium.CallbackProperty((result) => {
          //     let coordinates = [ 
          //       [ 111.69962882995605, 29.12888405176038, 500 ],
          //       [ 111.69842720031738, 29.1246103640853, 400 ],
          //       [ 111.70250415802002, 29.12191110140796, 300 ],
          //       [ 111.70456409454346, 29.123973044564462, 200 ],
          //       [ 111.69962882995605, 29.12888405176038, 500 ],
          //       // [ 111.69962882995605, 29.12888405176038 ],
          //       // [ 111.69842720031738, 29.1246103640853 ],
          //       // [ 111.70250415802002, 29.12191110140796 ],
          //       // [ 111.70456409454346, 29.123973044564462 ],
          //       // [ 111.69962882995605, 29.12888405176038 ],
          //     ].map(item => {
          //       return this.$map.lnglatToCartesian(...item);
          //     });
          //     let polygon = new Cesium.PolygonHierarchy(coordinates)
          //     return polygon;
          //   }, false),
          //   // height: 100, // 设置每个点的高度时，height不生效
          //   perPositionHeight: true, // 设置每个点的高度
          //   // extrudedHeight: 100,
          //   color: "#0000ff",
          //   outlineWidth: 5,
          //   outlineColor: "#ff0000"
          // }
        });
        
        this.testLayer.entities.add(entity);
        this.$map.flyToEntity(entity);
      }
      if(type === "resetEntity") {
        let entity = this.testLayer.entities.getById("createEntity");
        this.$map.resetEntity(entity, {
          billboard: {
            image: "https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png",
            // clampToGround: true,
            // width: 30,
            // height: 50,
            // verticalOrigin: "TOP",
            // horizontalOrigin: "LEFT",
            // offset: [-100, -100],
            // displayDistance: [0, 5000]
          },
        });
        console.log('log--- entity', entity);
      }
      if(type === "geojsonToEntities") {
        let zhengzhou = await axios.get("/data/zhengzhou.geojson");
        console.log('log--- zhengzhou', zhengzhou);
        let zhengzhouEntities = await this.$map.geojsonToEntities(zhengzhou.data, {
          polygon: {
            color: "rgba(255,0,0,0.2)",
            outlineWidth: 3,
            outlineColor: "#ffffff"
          },
        });
        zhengzhouEntities.forEach(item => {
          this.testLayer.entities.add(item);
        });
        axios.get("/data/area.geojson").then(async ({data: res}) => {
          console.log('log--- res', res);
          this.$map.addGeojsonDataSource(res, {clampToGround: true}, true);
          // let entities = await this.$map.geojsonToEntities(res, {
          //   // billboard: {
          //   //   image: "https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
          //   //   clampToGround: true,
          //   //   // width: 30,
          //   //   // height: 50,
          //   //   // verticalOrigin: "TOP",
          //   //   // horizontalOrigin: "LEFT",
          //   //   // offset: [-100, -100],
          //   //   // displayDistance: [0, 5000]
          //   // },
          //   // // 添加文字
          //   // label: {
          //   //   text: "测试文字显示",
          //   //   size: 20,
          //   //   color: '#ffff00',
          //   //   backgroundColor: "rgba(0, 0, 0, 0.8)",
          //   //   offset: [0, -100],
          //   //   clampToGround: true
          //   // },
          //   name: "测试区域",
          //   polygon: {
          //     color: "rgba(15,185,141,0.9)",
          //     outlineWidth: 5,
          //     outlineColor: "rgba(15,185,141,0.9)"
          //   },
          //   // polyline: {
          //   //   width: 5,
          //   //   color: "rgba(15,185,141,0.9)",
          //   // }
          // });
          let num = 0;
          let entities = await this.$map.geojsonToEntities(res, (entity) => {
            console.log('log--- entity', entity);
            num += 1;
            let properties = this.$map.resetCesiumProperty(entity.properties);
            console.log('log--- properties', properties);
            let center = this.$map.getEntityCenter(entity);
            console.log('log--- center', center);
            return {
              position: center,
              // billboard: {
              //   image: "https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
              //   clampToGround: true,
              //   // width: 30,
              //   // height: 50,
              //   // verticalOrigin: "TOP",
              //   // horizontalOrigin: "LEFT",
              //   // offset: [-100, -100],
              //   // displayDistance: [0, 5000]
              // },
              // 添加文字
              label: {
                text: properties.name,
                size: 20,
                color: num > 2 ? '#ffff00' : '#ff0000',
                backgroundColor: "rgba(0, 0, 0, 0.8)",
                clampToGround: true
              },
              polygon: {
                color: "rgba(15,185,141,0.9)",
                outlineWidth: 5,
                outlineColor: "rgba(15,185,141,0.9)"
              },
            }
          });
          console.log('log--- entities', entities);
          entities.forEach(item => {
            this.testLayer.entities.add(item);
          });
        });
      }
      if(type === "getEntityByProperty") {
        let entity = this.$map.getEntityByProperty(this.testLayer, "name", "中原区");
        console.log('log--- entity', entity);
      }
      if(type === "lookAt") {
        let lng = 111.69250030790069;
        let heading = 0;
        let height = 100;
        let entity = this.$map.createEntity({
          position: new Cesium.CallbackProperty((time, result) => {
            lng += 0.000005;
            heading += 0.1;
            height += 1;
            let position = Cesium.Cartesian3.fromDegrees(lng, 29.10669917422693, height);
            let orientation = this.$map.getOrientation(position, {
              heading,
              pitch: 0,
              roll: 0
            });
            entity.orientation = orientation;
            this.$map.lookAt(position, {
              heading: 90 + heading,
              pitch: 0,
            });
            return position
          }),
          /**
           * 添加模型
           */
          model: {
            url: "./model/CesiumDrone.glb",
            scale: 1,
            // clampToGround: true
          },
        });
        this.testLayer.entities.add(entity);
        // this.$map.flyToEntity(entity, {
        //   duration: 0
        // });
        console.log('log--- entity', entity);
        // this.$map.lookAt(entity, {
        //   // distance: 50
        // });
        // setTimeout(() => {
        //   this.$map.lookAt(undefined);
        // }, 2000)

        // 物体追踪
        // this.$map.trackEntity(entity);
        // setTimeout(() => {
        //   // 关闭物体追踪
        //   this.$map.trackEntity(undefined);
        // }, 2000)
      }
      if(type == "addParticleWindy") {
        axios.get("/data/demo_china.nc", {
          responseType: "blob"
        }).then(res => {
          this.particleWindy = this.$map.addParticleWindy({
            blobFile: res.data,
            windParams: {
              maxParticles: 10000,
              particleHeight: 1000.0,
              fadeOpacity: 0.996,
              dropRate: 0.003,
              dropRateBump: 0.01,
              speedFactor: 1.0,
              lineWidth: 4.0,
              dynamic: true
            },
            fields: {
              lev: "height_above_ground",
              U: "u-component_of_wind_height_above_ground",
              V: "v-component_of_wind_height_above_ground"
            }
          });
          console.log('log--- particleWindy', this.particleWindy);
        });
      }
      if(type === "removeParticleWindy") {
        if(this.particleWindy) this.particleWindy.remove();
      }
      if(type === "addDroneModel") {
        this.$map.viewController.resetView();
        this.$map.clearDataSource(this.modelLayer);
        this.modelEntity = null;
        if(this.viewTimer) clearInterval(this.viewTimer);
        let flyInfo = {
          lng: 113.655979,
          lat: 34.752383,
          height: 20,
          heading: 0,
          pitch: -45,
          roll: 0
        }
        let count = 0;
        this.addDroneModel(flyInfo);
        this.viewTimer = setInterval(() => {
          if(count < 10) {
            flyInfo.lng += 0.0001
          }else {
            flyInfo.lng -= 0.0001
          };
          if(count < 30) {
            flyInfo.lat += 0.0001
          }else {
            flyInfo.lat -= 0.0001
          };
          // flyInfo.height += 1;
          flyInfo.heading += 1;
          // flyInfo.pitch -= 1;
          // flyInfo.roll += 1;
          this.addDroneModel(flyInfo);
        }, 1000);
      }
    },
    changeCameraView(evt) {
      let value = evt.target.value;
      this.cameraType = value;
      if(value === "resetView") {//重置视角
        this.$map.viewController.resetView();
      }
      if(value === "setFixedView") {//固定视角
        this.$map.viewController.resetView();
        this.$map.viewController.setFixedView({
          position: this.positionProperty,
          heading: this.headingProperty,
        });
      }
      if(value === "setFrontView") {//第一视角
        this.$map.viewController.resetView();
        this.$map.viewController.setFrontView({
          position: this.positionProperty,
          heading: this.headingProperty,
          pitch: this.pitchProperty,
          roll: this.rollProperty,
        });
      }
      if(value === "setTrackView") {//第三视角
        this.$map.viewController.resetView();
        this.$map.viewController.setTrackView(this.modelEntity);
      }
    },
    // 添加无人机动态模型
    addDroneModel(flyInfo = {}) {
      let { lng, lat, height, heading, pitch, roll } = flyInfo;
      let position = this.$map.lnglatToCartesian(lng, lat, height);
      // this.viewShed.updateView(position, heading, pitch);
      if(!this.modelEntity) {
        let currentTime = Cesium.JulianDate.fromDate(new Date());
        // 设置位置动态属性
        this.positionProperty = new Cesium.SampledPositionProperty();
        this.positionProperty.addSample(currentTime, position);
        // 设置偏航角动态属性
        this.headingProperty = new Cesium.SampledProperty(Number);
        this.headingProperty.addSample(currentTime, heading);
        // 设置俯仰角动态属性
        this.pitchProperty = new Cesium.SampledProperty(Number);
        this.pitchProperty.addSample(currentTime, pitch);
        // 设置横滚角动态属性
        this.rollProperty = new Cesium.SampledProperty(Number);
        this.rollProperty.addSample(currentTime, roll);

        this.modelEntity = this.$map.createEntity({
          position: this.positionProperty,
          orientation: new Cesium.CallbackProperty((time, result) => {
            let timePosition = this.positionProperty.getValue(time);
            let timeHeading = this.headingProperty.getValue(time);
            let timePitch = this.pitchProperty.getValue(time);
            let timeRoll = this.rollProperty.getValue(time);

            // this.viewShed.updateView(timePosition, timeHeading, timePitch);
            this.VideoShed.updateView(timePosition, timeHeading, timePitch);
            // this.cesiumVideo3d.cameraPosition = timePosition;

            let orientation = this.$map.getOrientation(timePosition, {
              heading: timeHeading + 270,
              pitch: timePitch,
              roll: timeRoll
            });
            return orientation;
          }),
          model: {
            url: "/model/CesiumDrone.glb"
          }
        });
        this.modelLayer.entities.add(this.modelEntity);
      }else {
        let sampleDate = Cesium.JulianDate.fromDate(new Date());
        // 日期延长添加，否则推送位置太慢，会出现闪烁问题
        Cesium.JulianDate.addSeconds(sampleDate, 1, sampleDate);
        this.positionProperty.addSample(sampleDate, position);
        this.headingProperty.addSample(sampleDate, heading);
        this.pitchProperty.addSample(sampleDate, pitch);
        this.rollProperty.addSample(sampleDate, roll);
      }
    },
  }
}
</script>

<style scoped>
.map-wrap {
  height: 100%;
  position: relative;
}
.map-tool {
  position: absolute;
  left: 0;
  top: 0;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}
.map-tool span {
  display: inline-block;
  margin: 3px;
  padding: 3px 5px;
  border: 1px solid #333;
  background-color: #eee;
  border-radius: 3px;
  cursor: pointer;
}
.map-tool select {
  display: inline-block;
  margin: 3px;
  padding: 5px;
  outline: none;
  border: 1px solid #333;
  background-color: #eee;
  border-radius: 3px;
  cursor: pointer;
}
</style>